package org.gaaidou.ptarmigan.springboot.core.serialize.xml;


import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.gaaidou.ptarmigan.springboot.core.serialize.DateConverter;
import org.gaaidou.ptarmigan.springboot.core.serialize.StringConverter;
import org.gaaidou.ptarmigan.springboot.core.serialize.json.DefaultAnnotationIntrospector;
import org.gaaidou.ptarmigan.springboot.core.serialize.json.EnumConverter;

import java.util.Date;


public class XmlMapperFactory {
    public static XmlMapper getInstance() {
        return SingletonHolder.instance;
    }

    private static class SingletonHolder {
        private static final XmlMapper instance = new XmlMapper();

        static {
            SimpleModule module = new SimpleModule();
            module.addDeserializer(Date.class, new DateConverter())
                    .addDeserializer(Enum.class, new EnumConverter())
                    .addDeserializer(String.class, new StringConverter())
                    .addSerializer(Long.class, ToStringSerializer.instance)
                    .addSerializer(long.class, ToStringSerializer.instance)
                    .addSerializer(Long.TYPE, ToStringSerializer.instance);
            instance.registerModule(module);

            instance.setSerializationInclusion(JsonInclude.Include.NON_NULL);

            AnnotationIntrospector sis = instance.getSerializationConfig().getAnnotationIntrospector();
            AnnotationIntrospector dis = instance.getDeserializationConfig().getAnnotationIntrospector();

            AnnotationIntrospector is1 = AnnotationIntrospectorPair.pair(sis, new DefaultAnnotationIntrospector());
            AnnotationIntrospector is2 = AnnotationIntrospectorPair.pair(dis, new DefaultAnnotationIntrospector());

            instance.setAnnotationIntrospectors(is1, is2);

        }
    }

}
